package me.zhengjie.modules.website.service.impl;

import me.zhengjie.modules.website.domain.Theme;
import me.zhengjie.modules.website.repository.ThemeRepository;
import me.zhengjie.modules.website.repository.ThemeSpecifications;
import me.zhengjie.modules.website.service.ThemeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import me.zhengjie.modules.website.domain.PageResult;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import javax.persistence.criteria.Predicate;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;

/**
 * @author system
 * @since 2024-10-13 09:38:00
 */
@Service
public class ThemeServiceImpl implements ThemeService {

    @Autowired
    private ThemeRepository themeRepository;

    @Override
    public PageResult<Theme> findPage(Theme theme, Pageable pageable) {
        Page<Theme> page = themeRepository.findAll(ThemeSpecifications.queryList(theme), pageable);
        PageResult<Theme> result = new PageResult();
        result.setContent(page.getContent());
        result.setTotalElements(page.getTotalElements());
        return result;
    }

    @Override
    public PageResult<Theme> findPage(Theme theme, LocalDateTime startDate, LocalDateTime endDate, Pageable pageable) {
        Page<Theme> page = themeRepository.findAll((root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 通过反射遍历 Theme 的所有字段，过滤静态字段
            for (Field field : Theme.class.getDeclaredFields()) {
                field.setAccessible(true); // 允许访问私有字段

                // 跳过静态字段
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                }

                try {
                    Object value = field.get(theme); // 获取字段值
                    if (value != null) { // 如果字段不为空，添加查询条件
                        predicates.add(criteriaBuilder.equal(root.get(field.getName()), value));
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

            // 时间范围条件
            if (startDate != null) {
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"), Timestamp.valueOf(startDate)));
            }
            if (endDate != null) {
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime"), Timestamp.valueOf(endDate)));
            }

            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        }, pageable);

        PageResult<Theme> result = new PageResult<>();
        result.setContent(page.getContent());
        result.setTotalElements(page.getTotalElements());
        return result;
    }


    @Override
    public List<Theme> findList(Theme theme) {
        return themeRepository.findAll(ThemeSpecifications.queryList(theme));
    }

    @Override
    public Theme findById(Long id) {
        return themeRepository.findById(id).orElse(null);
    }

    @Override
    public Theme insert(Theme theme) {
        return themeRepository.save(theme);
    }

    @Override
    public Theme update(Theme theme) {
        return themeRepository.saveAndFlush(theme);
    }

    @Override
    public void delete(Long id) {
        themeRepository.deleteById(id);
    }

    /**
     * 切换主题启用状态
     *
     * @param newThemeId 新主题ID
     */
    @Transactional
    @Override
    public void switchTheme(Long newThemeId) {
        // 查询当前启用的主题
        Optional<Theme> currentEnabledTheme = themeRepository.findByIsEnabledTrue();

        // 将当前启用的主题设置为 false
        if (currentEnabledTheme.isPresent()) {
            Theme theme = currentEnabledTheme.get();
            theme.setIsEnabled(false);
            themeRepository.save(theme);
        }

        // 启用新的主题
        Optional<Theme> newTheme = themeRepository.findById(newThemeId);
        if (newTheme.isPresent()) {
            Theme theme = newTheme.get();
            theme.setIsEnabled(true);
            themeRepository.save(theme);
        } else {
            throw new RuntimeException("主题ID无效");
        }
    }


    @Override
    public Theme getEnabledTheme() {
        return themeRepository.findFirstByIsEnabledTrue();
    }

}